###############################################################################
#                                                                             #
#    This file is part of the testsuite of the "ssbot" Python module.         #
#    It is distributed under the MIT License. See LICENSE.txt for details.    #
#                                                                             #
###############################################################################


import multiprocessing
import os
import sys
import time
import unittest
import urllib

sys.path.append('../')

import ssbot.schedulers


class UiRendererTests(unittest.TestCase):
    def setUp(self):
        self.ui_test_file = 'helpers/.ui_test.html'
        self.test_text = 'test_text'
        with open(self.ui_test_file, 'w') as f:
            f.write(self.test_text)

    def tearDown(self):
        if os.path.exists(self.ui_test_file):
            os.remove(self.ui_test_file)

    def test_basic_rendering(self):
        port = 8010
        base_url = 'http://localhost'
        scheduler_name = 'sched'
        p = multiprocessing.Process(target=ssbot.schedulers.UiRenderer(
            base_url, port, scheduler_name, None, None))
        p.start()
        time.sleep(2)
        try:
            url = '%s:%d/%s/%s' % (base_url, port,
                                   scheduler_name, self.ui_test_file)
            ui_file = urllib.urlopen(url)
            content = ui_file.read()
            ui_file.close()
            p.terminate()
        except IOError:
            p.terminate()
            self.fail('Unable to fetch URL. Renderer is probably not up.')
        self.assertTrue(self.test_text in content)


if __name__ == '__main__':
    unittest.main()
